import { Component, Input, Output, forwardRef, EventEmitter, ViewChild } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import {NgxNeditorComponent} from '@notadd/ngx-neditor';
import { environment } from '@env/environment';
import { UrlManager } from '../url/url.manager';

/**
 * 定义富文本编辑器实例 UE
 */
declare const UE;

@Component({
  selector: 'app-ueditor',
  template: `<ngx-neditor [(ngModel)]="data" [loadingTip]="'加载中……'" [config]="_config" (onPreReady)="onPreReady($event)" (onReady)="onReady($event)" #full></ngx-neditor>`,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => UeditorComponent),
    multi: true
  }]
})

export class UeditorComponent implements ControlValueAccessor {

  @ViewChild('full')
  full: NgxNeditorComponent;

  private propagateChange: any = {};

  _config: object = {
    serverUrl: environment.serverUrl + UrlManager.ueditor.ueditorConfig,
    zIndex: 995,
    theme: 'notadd',
    initialFrameHeight: 150
  };

  private _data: string;

  get data() {
    return this._data;
  }

  set data(data: string) {
    if (data !== this._data) {
      this._data = data;
      this.propagateChange(this._data);
    }
  }

  /**
   * 前端配置，参考：http://fex.baidu.com/ueditor/#start-config
   */
  @Input('config')
  set config(config: object) {
    this._config = Object.assign({}, config, this._config);
  }

  @Output() ready: EventEmitter<NgxNeditorComponent> = new EventEmitter<NgxNeditorComponent>();

  writeValue(val: string): void {
    if (val !== this._data) {
      this._data = val;
    }
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void { }

  onPreReady(ue: NgxNeditorComponent): void {
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
      let url = this._bkGetActionUrl.call(this, action);
      debugger
      switch(action) {
        case 'listimage':
          url = ue.config.serverUrl + UrlManager.ueditor.imageList;
          break;
        case 'uploadimage':
        case 'uploadscrawl':
          url = ue.config.serverUrl + UrlManager.ueditor.uploadImage;
          break;
        case 'uploadvideo':
          url = ue.config.serverUrl + UrlManager.ueditor.uploadVideo;
          break;
        default:
          this._bkGetActionUrl.call(this, action);
      }
      return url;
    }
  }

  onReady(ue: NgxNeditorComponent): void {
    this.ready.emit(ue);
  }
}
